package com.itheima.service.impl;

import com.itheima.common.exception.OrderBusinessException;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderDTO;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Override
    public void submitOrder(OrderDTO orderDTO) {
//        2. 校验用户输入的验证码是否正确。
        String validateCode = (String) redisTemplate.opsForValue().get(orderDTO.getTelephone());
        if(!orderDTO.getValidateCode().equals(validateCode)){
            throw new OrderBusinessException("验证码输入错误");
        }
//        3. 预约日期的预约人数没有设置的话不能预约。
        OrderSetting orderSetting = orderMapper.findOrderSettingByOrderDate(orderDTO.getOrderDate());
        if(orderSetting == null ){
            throw new OrderBusinessException("预约日期没有设置");
        }
//        4. 预约日期是否已经约满，如果已经约满则无法预约。
        if(orderSetting.getReservations() >= orderSetting.getNumber()){
            throw new OrderBusinessException("预约日期已经约满");
        }
//        6. 当前用户不是会员，需要自动完成注册。
        Member member = orderMapper.findMemberByIdCard(orderDTO.getIdCard());
        if(member == null){
            member = Member.builder()
                    .idCard(orderDTO.getIdCard())
                    .name(orderDTO.getName())
                    .sex(orderDTO.getSex())
                    .phoneNumber(orderDTO.getTelephone())
                    .build();
            memberMapper.insertMember(member);
        }
        Integer id = member.getId();
//        5. 不能重复预约（同一个用户在同一天预约了同一个套餐）。
        Order order = orderMapper.findByMemberIdAndOrderDateAndSetmealId(id,orderDTO.getOrderDate(),orderDTO.getSetmealId());
        if(order != null){
            throw new OrderBusinessException("不能重复预约");
        }
//        7. 更新已预约人数
        order = Order.builder()
                .memberId(id)
                .orderDate(orderDTO.getOrderDate())
                .orderType(Order.ORDERTYPE_TELEPHONE)
                .orderStatus(Order.ORDERSTATUS_NO)
                .setmealId(orderDTO.getSetmealId())
                .build();
        orderMapper.insert(order);
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingMapper.update(orderSetting);
    }
}
